package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> page(@RequestParam(required = false, defaultValue = "1") Integer page,
                        @RequestParam(required = false, defaultValue = "10") Integer pageSize, String name) {
        log.info("菜品管理查询 page={}", page);
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);
//        执行分页查询
        dishService.page(pageInfo, wrapper);

        /*
         *
         * 完善代码*/
        //封装数据-total
        Page<DishDto> dishDtoPage = new Page<>();
        dishDtoPage.setTotal(pageInfo.getTotal());
        //封装数据-records
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //根据id查询分类对象
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }


    /*
     *
     *     新增菜品
     * */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        dishService.savaDishFlavors(dishDto);
        //清理某个分类下的缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        log.info("新增菜品，删除redis缓存");
        return R.success("新增菜品成功");
    }

    /*
     *   根据条件查询对应的菜品数据
     *
     * */

//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//        //构造查询条件
//        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        //添加条件，状态改为1(起售状态)的菜品
//        wrapper.eq(Dish::getStatus, "1");
//        //添加排序条件(排序-更新时间)
//        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(wrapper);
//        return R.success(list);
//    }

    /*
     *   根据条件查询对应的菜品数据
     *
     * */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //先查询redis,如果有数据直接返回
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //下面是集合类型所以需要强转成List
        List<DishDto> redisList = (List<DishDto>) redisTemplate.opsForValue().get(key);
      if (!CollectionUtils.isEmpty(redisList)){
          log.info("查询redis,redis中有缓存数据,直接返回,无需数据库");
          return R.success(redisList);
      }

        //构造查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，状态改为1(起售状态)的菜品
        wrapper.eq(Dish::getStatus, "1");
        //添加排序条件(排序-更新时间)
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(wrapper);

        //---------------完善功能
        List<DishDto> dtoList = dishList.stream().map(dish1 -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            //封装属性
            Category category = categoryService.getById(dish1.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(dish1.getName());
            }
            //组装条件
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());

        //数据存储到redis
        log.info("查询数据库，存储到redis");
        redisTemplate.opsForValue().set(key,dtoList,24, TimeUnit.HOURS);

        return R.success(dtoList);
    }


    /*
     * 根据id查询菜品信息和对应的口味信息
     *
     * */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        if (dishDto != null) {
            return R.success(dishDto);
        }
        return R.error("未查询到菜品");
    }

    /*
    * 修改
    * */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info("更新菜品，dishDto={}", dishDto);
        dishService.updateWithFlavor(dishDto);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改菜品成功");
    }


    /*
     * 停售
     *
     * */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        dishService.updateStatus(status,ids);
        return R.success();
    }

/*
* 删除
* */

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        dishService.removeWithFlavors(ids);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        log.info("删除菜品，清理缓存数据");
        return R.success("菜品数据删除成功");
    }
}
